package com.xbq.exceleditor.ui

import android.os.Bundle
import android.view.View
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import com.blankj.utilcode.util.ToastUtils
import com.gyf.immersionbar.ktx.immersionBar
import com.xbq.exceleditor.OFFICE_TYPE
import com.xbq.exceleditor.R
import com.xbq.exceleditor.adapter.JinxuanCollectionsAdapter
import com.xbq.exceleditor.databinding.FragmentVideoCourseBinding
import com.xbq.xbqsdk.component.activity.VBFragment
import com.xbq.xbqsdk.component.recyleview.LinearSpaceDecoration
import com.xbq.xbqsdk.core.event.UserInfoChanged
import com.xbq.xbqsdk.net.officeeditor.OfficeEditorApi
import com.xbq.xbqsdk.net.officeeditor.dto.CollectionsByTypeDto
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import javax.inject.Inject

/**
 * Author: liaohaiping
 * Time: 2020-10-24
 * Description:
 */
@AndroidEntryPoint
class VideoCourseFragment :
    VBFragment<FragmentVideoCourseBinding>() {
    @Inject
    lateinit var officeEditorApi: OfficeEditorApi
    @Inject
    lateinit var collectionAdapter: JinxuanCollectionsAdapter


    override fun useEventBus(): Boolean {
        return true
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        binding.adview.init("videocoursefragment",requireActivity())
        initRecyclerView()
        loadVideoCollections()
    }

    private fun initRecyclerView() {
        binding.videoCollectionList.let {
            it.layoutManager = LinearLayoutManager(context)
            it.addItemDecoration(LinearSpaceDecoration(8f))
            it.adapter = collectionAdapter
            collectionAdapter.setOnItemClickListener { ad, view, position ->
                val item = collectionAdapter.getItem(position)
                PlayVideoActivity.start(item)
            }
        }
    }

    private fun loadVideoCollections() {
        lifecycleScope.launch {
            val res =
                officeEditorApi.collections_by_type(CollectionsByTypeDto(OFFICE_TYPE, "精选", 10))
            if (res.success()) {
                collectionAdapter.setNewDatas(res.data!!)
            } else {
                ToastUtils.showShort(res.message)
            }
        }
    }

    override fun onResume() {
        super.onResume()
        immersionBar {
            statusBarView(R.id.statusbar)
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onUserInfoChanged(userInfoChanged: UserInfoChanged) {
        loadVideoCollections()
    }


}